<template>
  <div class="identity-card">
    <span>控件类型</span>
    <span>身份证</span>
  </div>
  <div class="identity-card-img">
    <div class="title">拍摄/上传您的二代身份证</div>
    <div class="content">图片大小不超过10M,仅限png.jpg.jpeg.bmp格式文件</div>
    <div class="uplader-img">
      <van-uploader
        v-model="fileImage.just"
        :max-size="10 * 1024 * 1024"
        :max-count="1"
        @oversize="onOversize"
      >
        <template #default>
          <div class="file-last-time">
            <svg-icon name="camera" />
            <span class="id-number-img">点击拍摄/上传人像面</span>
          </div>
        </template>
      </van-uploader>
      <van-uploader
        v-model="fileImage.against"
        :max-size="10 * 1024 * 1024"
        :max-count="1"
        @oversize="onOversize"
      >
        <div class="file-last-time">
          <svg-icon name="camera" />
          <span class="id-number-img">点击拍摄/上传国徽面</span>
        </div>
      </van-uploader>
    </div>
  </div>
  <div class="cell">
    <van-icon name="info" color="#1989fa" size="14" />
    <span class="cell-text">以下信息自动识别，如识别有误，请重新上传。</span>
  </div>
  <van-form ref="formRef" @submit="onSubmit">
    <van-field
      class="field-name"
      v-model="userInfo.realName"
      center
      readonly
      label="真实姓名"
      placeholder="从上传图片中自动识别"
    />
    <van-field
      class="field-name"
      v-model="userInfo.identityCard"
      center
      readonly
      label="身份证号"
      placeholder="从上传图片中自动识别"
    />
    <van-field
      class="field-name"
      v-model="userInfo.mobile"
      center
      clearable
      name="mobile"
      label="手机号码"
      placeholder="请输入您的手机号码"
      :rules="FormRules.mobile"
    />
    <van-field
      class="field-name"
      v-model="userInfo.code"
      center
      clearable
      name="code"
      label="验证码"
      placeholder="请输入短信验证码"
      :rules="FormRules.code"
    >
      <template #button>
        <van-count-down
          v-if="isCountDownShow"
          :time="countDown * 1000"
          format="ss s"
          @finish="isCountDownShow = false"
        />
        <van-button
          v-else
          class="code-btn"
          native-type="button"
          size="small"
          type="default"
          @click="sendCodeClick"
          >获取验证码</van-button
        >
      </template>
    </van-field>
  </van-form>
  <div class="mobile-end">
    <van-button class="mobile-end-btn" block type="primary" @click="send"
      >下一步</van-button
    >
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch } from 'vue'
import { useStore } from '@/store'
import { useRouter, useRoute } from 'vue-router'
import { FormInstance, Toast } from 'vant'
import { FormRules } from '@/hooks/form-config'
import { generateUUID } from '@/utils/global-method'
import { getSendCode, getValidateMobileCode } from '@/api/login'
import {
  postUploadingIdCard,
  postIdcardInfoAuth,
  postChangeAlertState
} from '@/api/face-swiping'
export default defineComponent({
  setup() {
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    // 用户信息
    const fileImage = reactive({
      just: [],
      against: []
    })
    const formRef = ref<FormInstance>()
    const userInfo = reactive({
      realName: '',
      identityCard: '',
      mobile: '',
      code: '',
      randomCode: ''
    })
    // 发送验证码
    const isCountDownShow = ref(false)
    const countDown = ref(0)
    const sendCodeClick = async () => {
      try {
        await formRef.value?.validate('mobile')
      } catch (error) {
        return error
      }
      try {
        userInfo.randomCode = generateUUID()
        const params = {
          mobile: userInfo.mobile,
          randomCode: userInfo.randomCode
        }
        const res = await getSendCode(params)
        if (res.code !== '0') return
        countDown.value = Math.floor((res.data - new Date().getTime()) / 1000)
        isCountDownShow.value = true
      } catch (error) {
        return error
      }
    }
    // 上传身份证
    watch(fileImage, async (newVal: any) => {
      if (newVal.just.length && newVal.against.length) {
        const params = {
          positive: newVal.just[0].content.replace(
            /^data:image\/\w+;base64,/,
            ''
          ),
          reverse: newVal.against[0].content.replace(
            /^data:image\/\w+;base64,/,
            ''
          )
        }
        const res = await postUploadingIdCard(params)
        if (res.code !== '0') return
        userInfo.realName = res.data.realName
        userInfo.identityCard = res.data.idcard
      }
    })
    // 文件上传过大
    const onOversize = () => {
      Toast('文件大小不能超过 10Mb')
    }
    // 下一步
    const send = () => {
      if (!fileImage.against.length || !fileImage.just.length) {
        return Toast('请先上传身份证')
      }
      formRef.value!.submit()
    }
    const onSubmit = async () => {
      const params = {
        mobile: userInfo.mobile,
        captchaCode: userInfo.code,
        randomCode: userInfo.randomCode
      }
      // 校验验证码
      const res = await getValidateMobileCode(params)
      if (res.code !== '0') return
      const paramsA = {
        certificateNumber: userInfo.identityCard,
        name: userInfo.realName
      }
      const resA = await postIdcardInfoAuth(paramsA)
      if (resA.code !== '0') return
      const paramsB = {
        userId: store.state.login.userInfo.userId,
        status: 1
      }
      const resB = await postChangeAlertState(paramsB)
      if (resB.code !== '0') return
      router.push({
        path: '/real-face-success',
        query: {
          contratId: route.query.contratId
        }
      })
    }

    return {
      FormRules,
      userInfo,
      fileImage,
      formRef,
      isCountDownShow,
      countDown,
      onSubmit,
      onOversize,
      sendCodeClick,
      send
    }
  }
})
</script>

<style scoped lang="less">
.identity-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 54px;
  margin: 10px 0;
  padding: 0 20px;
  background-color: #fff;
  font-size: 15px;
  color: #101010;
}
.identity-card-img {
  background-color: #fff;
  padding: 20px;
  .title {
    margin-bottom: 10px;
    font-size: 15px;
    color: #101010;
  }
  .content {
    font-size: 12px;
    color: #999;
  }
  .uplader-img {
    display: flex;
    justify-content: space-between;
    padding-top: 20px;
    .file-last-time {
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      align-items: center;
      width: 160px;
      height: 100px;
      border: 1px dashed #e4e4e4;
      .id-number-img {
        font-size: 12px;
        color: #2489f2;
      }
    }
    :deep(.van-uploader__preview) {
      margin: 0;
    }
    :deep(.van-image) {
      width: 160px;
      height: 100px;
    }
  }
}
.cell {
  height: 34px;
  line-height: 34px;
  padding: 0 20px;
  font-size: 12px;
  color: #999;
  .cell-text {
    padding-left: 4px;
  }
}
.field-name {
  height: 54px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 15px;
  color: #101010;
  .code-btn {
    color: #a5a5a5;
  }
}
.mobile-end {
  margin-top: 10px;
  padding: 10px 20px;
  background-color: #fff;
  .mobile-end-btn {
    font-size: 17px;
  }
}
</style>
